<?php
if(!defined('FROM_INDEX'))exit('Invalid request');

require_once ROOT_PATH.'include/sql/class_db.php';
require_once ROOT_PATH.'include/sql/base.sql.php';

class TagSqlFunc extends BaseSqlFunc
{
	/**
	 *
	 * 根据ID获取话题信息
	 * @param unknown_type $id
	 */
	function get($id)
	{
		$sql = <<<SQL
select
	t.*
from
	`{$this->pre}tag` t
where
	t.`id` = ?
	or t.`name` = ?
SQL;

		$result = DBFunction::getInstance()->getRow($sql, array($id, $id));
		return check_array($result) ? $result : array();
	}

	/**
	 *
	 * 搜索话题
	 * @param array $request
	 */
	function search($request)
	{
		$tag = '%'.$request['tag'].'%';
		$limit = $request['page_size'];
		$num = $request['page_index'];

		$sql = <<<SQL
select
	t.id, t.name, t.user_id, t.create_time
from
	`{$this->pre}tag` t
where
	t.`name` like ?
SQL;

		$result = DBFunction::getInstance()->selectLimit($sql,$limit, $num, array($tag));

		return check_array($result) ? $result : array();
	}

	/**
	 *
	 * 热门话题
	 */
	function hot($request)
	{
		$time = time()-7*24*3600;
		$limit = $request['page_size'];
		$num = $request['page_index'];

		$sql = <<<SQL
select
	t.id, t.name, t.user_id, t.create_time
from
	`{$this->pre}tag` t
where
	`update_time`>?
order by story_count desc
SQL;

		$result = DBFunction::getInstance()->selectLimit($sql,$limit, $num, array($time));

		return check_array($result) ? $result : array();
	}

	/**
	 *
	 * 新增话题
	 * @param array $request
	 */
	function add($request)
	{
		$time = time();

		$params = array(
		$request['name'],
		$request['uid'],
		$time,
		$time
		);

		$sql = <<<SQL
insert into `{$this->pre}tag`
	(`name`, `user_id`, `create_time`, `update_time`, `is_hot`, `story_count`)
values
	(?,?,?,?,0,0)
SQL;

		$result = DBFunction::getInstance()->insert($sql, $params);

		return ($result !== false) ? $result : false;
	}

	/**
	 *
	 * 更新话题
	 * @param array $request
	 */
	function update($request)
	{
		return false;
	}
	
	function update_story_count($tid)
	{
		$time = time();
		
		$sql = <<<SQL
update `{$this->pre}tag`
set
	`story_count` = `story_count`+1,
	`update_time`=?
where
	`id`=?
SQL;

		$result = DBFunction::getInstance()->execute($sql, array($time, $tid));

		return ($result !== false) ? true : false;
	}
	
	function delete($ids)
	{
		return false;
	}
}